#include "../http/HttpServer.h"
#include "../http/HttpData.h"
#include "../common/global.h"
#include "../common/CCReactor.h"
#include <iostream>
#include <string>
#include <thread>
#include <chrono>

int main() {
    std::cout << "HTTP Server Example" << std::endl;
    
    // Initialize global components
    g_reactor->Init();
    g_reactor->Start();
    
    // Create HTTP server
    HttpServer server;
    
    // Set up request handler
    auto handler = [&server](uint32_t handle, stHttpRequest&& req) -> int {
        std::cout << "Received request: " << req.method << " " << req.url << std::endl;
        
        // Print headers
        for (const auto& header : req.heads) {
            std::cout << "  " << header.first << ": " << header.second << std::endl;
        }
        
        // Create response
        stHttpResponse resp;
        resp.state = 200;
        resp.heads["Content-Type"] = "text/plain";
        resp.heads["Server"] = "HttpLib/1.0";
        resp.heads["Connection"] = "keep-alive";
        
        // Simple routing
        if (req.url == "/") {
            resp.body = "Hello, World!";
        } else if (req.url == "/test") {
            resp.body = "Test page";
        } else {
            resp.state = 404;
            resp.body = "Not Found";
        }
        
        // Send response
        server.Response(handle, std::move(resp));
        
        return 0;
    };
    
    // Start server
    if (server.Start("0.0.0.0", 8080, handler) != 0) {
        std::cerr << "Failed to start server" << std::endl;
        return 1;
    }
    
    std::cout << "Server started on http://0.0.0.0:8080" << std::endl;
    std::cout << "Press Ctrl+C to stop" << std::endl;
    
    // Wait for shutdown
    while (!g_shutdown_requested) {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    
    // Cleanup
    g_reactor->Stop();
    
    return 0;
}